#!/bin/bash

# shellcheck source=/dev/null
source "${JAliasSrc:?}/scripts/tool.bash"
source "${JAliasSrc:?}/scripts/core.sh"
source "${JAliasSrc:?}/scripts/jalias.sh"

# enter point
function jalias() {
    common=$1
    shift
    case "${common}" in
    "+" | "add")
        _jalias_add "${1}"
        source "${JAliasSrc:?}/scripts/jalias_env.sh"
        ;;
    "-" | "del")
        _jalias_del "${1}"
        source "${JAliasSrc:?}/scripts/jalias_env.sh"
        ;;
    "l")
        _jalias_list
        ;;
    "clean")
        _jalias_clean
        source "${JAliasSrc:?}/scripts/jalias_env.sh"
        ;;
    "-e")
        _path="$(_jalias_replace "${1}")"
        if [ ! -e "$_path" ]; then
            printf "\033[31m%s\033[0m\n" "● [jalias] enter mode: path $_path not existed "
            return 1
        fi
        cd "$_path" || exit
        shift
        printf "\033[32m%s\033[0m\n" "● [jalias] run ""$*"" in $_path"
        "$@"
        cd - || exit
        return 1
        ;;
    *)
        # `jalias proj` such as `jalias cd proj`
        output=""
        if [ $# -eq 0 ]; then
            pp=$common
            common="cd"
            output="$(_jalias_exec "$pp")"
        else
            output="$(_jalias_exec "$@")"
        fi
        eval "$common $output"
        ;;
    esac
}
